package com.wsoft.service.impl;

import com.wsoft.constant.RedisKeyConstant;
import com.wsoft.core.exception.Asserts;
import com.wsoft.core.service.RedisService;
import com.wsoft.service.IVerificationCodeService;
import com.wsoft.utils.VerificationCodeUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 验证码公共服务
 *
 * @author: juiet
 * @date: 2024年09月03日 10:52
 */
@Service
public class VerificationCodeServiceImpl implements IVerificationCodeService {
    @Resource
    private RedisService redisService;
    @Override
    public Map<String, String> initImageCode() {
        //设置Redis路径
        Map<String, String> result = new HashMap<>(16);
        VerificationCodeUtil verificationCodeUtil = new VerificationCodeUtil();
        //获取验证码
        String securityCode = verificationCodeUtil.getCode();

        String uuid = UUID.randomUUID().toString();
        //生成redis中的不重复的key
        String keyVerification = RedisKeyConstant.VERIFICATION_CODE + uuid;
        //     主键key     内容（验证码）    过期时间（120秒）
        redisService.set(keyVerification, securityCode.toUpperCase(), 120);
        //生成图片
        BufferedImage image = verificationCodeUtil.getBuffImg();

        //进行base64编码
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", bos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String string = Base64Utils.encodeToString(bos.toByteArray());
        result.put("codeKey", uuid);
        result.put("codeImage", string);
        result.put("codeValue",securityCode);
        return result;
    }

    @Override
    public void checkImageCode(String key, String code) {
        String imageCode = redisService.get(RedisKeyConstant.VERIFICATION_CODE+key) == null ? null : redisService.get(RedisKeyConstant.VERIFICATION_CODE+key).toString();
        if (imageCode == null) {
            //验证码已过期！
            Asserts.fail("[vcode.error.timeout]");
        }
        if (!code.toUpperCase().equals(imageCode.toUpperCase())) {
            //验证码错误！
            Asserts.fail("[vcode.error.check]");
        }
    }

}
